<?php
//namespace student\controller\welcome;
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller {


	public function __construct()
	{
		parent::__construct();
		//$this->load->model('');
		$this->load->helper('url_helper');
		$this->load->model("getuser");
		session_start();
	}

    
    /**
    ** 登录页面函数
    **/
	public function index()
	{
		//$this->load->view('welcome_message');
		$this->load->view('home/login');
		$this->load->view('home/bottom_detaildata');
	}


    /**
     *  验证用户登录函数
	*/
	public function verifyLogin()
	{
		//获取页面提交数据：用户名、密码、验证码
		$username = @$_REQUEST['username']?$_REQUEST['username']:"";
		$password = @$_REQUEST['password']?$_REQUEST['password']:"";
		$captcha = @$_REQUEST['verify_code']?$_REQUEST['verify_code']:'';
		

		//验证用户名和密码为空
		if($captcha != $_SESSION['code'] || $captcha == '')
		{
			print json_encode(array('code'=>1,'desc'=>'验证码输入错误','text'=>$_SESSION['code'],'te'=>$captcha));
			return 0;
		}

		if($username == '' || $password == '')
		{
			print json_encode(array('code'=>2,'desc'=>'用户名或密码为空'));
			return 0;
		}
        
        $resUser = $this->getuser->verifyLogin($username,$password);

        //验证用户名和密码正确性
        if(@!empty($resUser))
        {
        	$_SESSION['user_name'] = $username;
        	$_SESSION['user_id'] = $resUser['id'];
        	print json_encode(array('code'=>0,'desc'=>'登录成功','url'=>base_url()."index.php/home/datahub/index"));
        } else {
        	print json_encode(array('code'=>3,'desc'=>'用户名或密码错误'));
        }
	}


	/**
	*  退出函数
	**/
    public function logout()
    {
    	unset($_SESSION['user_name']);
    	unset($_SESSION['user_id']);
    	redirect(base_url().'index.php/home/index/index', 'refresh');
    }

	/**
	** 注册函数
	**/
	public function register()
	{
		$this->load->view('home/register');
		$this->load->view('home/bottom_detaildata');
	}


	/**
	** 注册验证函数
	**/
	public function verifyRegister()
	{
		$user_name = $_REQUEST['username'];
		$password = $_REQUEST['password'];
		$verify_code = $_REQUEST['verify_code'];

		if($verify_code == '' || $verify_code != $_SESSION['code']){
			print json_encode(array('code'=>1,'desc'=>"验证码不正确"));
			return 0;
		}

		$res = $this->getuser->verifyUser($user_name);

        //var_dump($res);exit;
		if(!empty($res)){
			print json_encode(array('code'=>2,'desc'=>"用户已存在"));
			return 0;
		}

		$tel = $user_name;
		$res = $this->getuser->addUser($tel,$password);
		if($res){
			$_SESSION['user_name'] = $user_name;
			$_SESSION['user_id'] = $res;
			print json_encode(array('code'=>0,'desc'=>"恭喜您，注册成功"));
		} else {
			print json_encode(array('code'=>4,'desc'=>'注册失败，请重新注册'));
		}	
	}

	/**
	** 用户个人信息主页
	**/
	public function showUserInfo()
	{
		$user_name = $_SESSION['user_name'];
		$user_id = $_SESSION['user_id'];
		
	}
}
